package com.lzy.business.facade;

import com.alibaba.fastjson.JSON;
import com.lzy.business.param.MemberBuyCouponParam;
import com.lzy.common.apis.CouponOrderLogServiceApi;
import com.lzy.common.dtos.CouponOrderLogDto;
import com.lzy.coupon.apis.CouponServiceApi;
import com.lzy.coupon.dtos.CouponDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.CollectionUtils;
import com.lzy.framework.core.utils.DateUtil;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.tools.date.DateUtils;
import com.lzy.member.apis.MemberCouponServiceApi;
import com.lzy.member.apis.MemberSaleLogServiceApi;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberCouponDto;
import com.lzy.member.dtos.MemberSaleLogDto;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.payment.apis.PayBillApi;
import com.lzy.payment.apis.PayMemberAccountApi;
import com.lzy.payment.constants.CommonConstants;
import com.lzy.payment.dtos.memberAccount.LzNumberDTO;
import com.lzy.payment.dtos.payBill.PayBillDTO;
import com.lzy.product.apis.MemberCouponsServiceApi;
import com.lzy.product.apis.OrderCouponServiceApi;
import com.lzy.product.apis.OrderProductServiceApi;
import com.lzy.product.apis.ProductInfoServiceApi;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.MemberCouponsDto;
import com.lzy.product.dtos.OrderCouponDto;
import com.lzy.product.dtos.OrderProductDto;
import com.lzy.product.dtos.ProductInfoDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.lzy.framework.tools.date.DateStyle.YYYY_MM_DD;

/**
 * 会员扫码购买业务流程
 */
@Component
public class MemberBuyFacade {

    private static final Logger LOGGER = LoggerFactory.getLogger(MemberBuyFacade.class);

    @Autowired
    private MemberSaleLogServiceApi memberSaleLogServiceApi;

    @Autowired
    private MemberCouponServiceApi memberCouponServiceApi;

    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;

    @Autowired
    private MemberUserServiceApi memberUserServiceApi;

    @Autowired
    private CouponServiceApi couponServiceApi;

    @Autowired
    private OrderCouponServiceApi orderCouponServiceApi;

    @Autowired
    private OrderProductServiceApi orderProductServiceApi;

    @Autowired
    private ProductInfoServiceApi productInfoServiceApi;

    @Autowired
    private CouponOrderLogServiceApi couponOrderLogServiceApi;

    @Autowired
    private PayMemberAccountApi payMemberAccountApi;

    @Autowired
    private PayBillApi payBillApi;

    /**
     * 会员通过销售商的二维码，扫码购买券
     *
     * @param saleManId 销售商会员id
     * @param memberId  购买方会员id
     * @param list      会员购买券对象（券类型、面额、数量）
     * @param orderId   订单号
     * @return
     */
    public Boolean memberBuyOfCode(Long saleManId, Long memberId, List<MemberBuyCouponParam> list, String orderId) {
        //1.获取当前场景销售员可卖的券列表
        System.out.println("卡券宝会员购买--------获取当前场景销售员可卖的券列表");
        List<MemberBuyCouponParam> saleCouponList = new ArrayList<>();
        if (!saleManId.equals(memberId))
            saleCouponList = checkSaleMan(saleManId, list);
        System.out.println("卡券宝会员购买--------获取当前场景销售员可卖的券列表" + JSON.toJSONString(list));

        //2.获取会员从龙之游购买的券列表
        System.out.println("卡券宝会员购买--------获取会员从龙之游购买的券列表");
        List<MemberBuyCouponParam> lzyCouponList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(saleCouponList))
            lzyCouponList = checkLzyCoupon(list, saleCouponList);
        System.out.println("卡券宝会员购买--------获取会员从龙之游购买的券列表" + JSON.toJSONString(list));

        //3.条件满足，直接购买
        //3.1.购买销售商的券
        System.out.println("卡券宝会员购买--------购买销售商的券------开始");
        if (CollectionUtils.isNotEmpty(saleCouponList)) {
            if (!memberId.equals(saleManId))
                Ensure.that(buyOfSaleMan(saleManId, memberId, saleCouponList, orderId)).isTrue("05000001");
        }
        System.out.println("卡券宝会员购买--------购买销售商的券------结束");

        //3.2.购买龙之游的券
        System.out.println("卡券宝会员购买--------购买龙之游的券------开始");
        if (CollectionUtils.isNotEmpty(lzyCouponList))
            Ensure.that(buyOfLzy(saleManId, memberId, lzyCouponList, orderId)).isTrue("05000001");
        System.out.println("卡券宝会员购买--------购买龙之游的券------结束");
        DataSourceHolder.clearDataSource();
        return Boolean.TRUE;
    }

    /**
     * 1.检测当前销售商拥有（当前会员购买的券）的数量
     *
     * @param saleManId 销售员会员id
     * @param list      会员购买券对象（券类型、面额、数量）
     */
    private List<MemberBuyCouponParam> checkSaleMan(Long saleManId, List<MemberBuyCouponParam> list) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        List<MemberCouponDto> memberCouponDtoList = memberCouponServiceApi.selectListByMemberId(saleManId);//销售商绑定的券
        List<MemberCouponDto> memberCouponDtoEnable = new ArrayList<>();//销售商目前可销售的券
        if (CollectionUtils.isNotEmpty(memberCouponDtoList))
            for (MemberCouponDto couponDto : memberCouponDtoList) {
                if (couponDto.getType() == 3 && couponDto.getCouponStatus() != null && couponDto.getCouponStatus().intValue() == 1) {//卡券宝产品绑定销售商的券
                    memberCouponDtoEnable.add(couponDto);
                }
            }
        List<MemberBuyCouponParam> returnList = new ArrayList<>();//返回结果集
        for (MemberBuyCouponParam memberBuyCouponParam : list) {//会员购买的条件
            MemberBuyCouponParam buyCouponParam = new MemberBuyCouponParam();
            buyCouponParam.setCouponType(memberBuyCouponParam.getCouponType());
            buyCouponParam.setCouponPrice(memberBuyCouponParam.getCouponPrice());
            Integer number = 0;//循环条件下，销售方可销售的数量
            List<Long> couponIdList = new ArrayList<>();//销售商即将销售的券id集合
            for (MemberCouponDto memberCouponDto : memberCouponDtoEnable) {//销售商可销售的券
                if (memberBuyCouponParam.getCouponType() != null && memberBuyCouponParam.getCouponType().toString().equals(memberCouponDto.getType().toString()) &&
                    memberBuyCouponParam.getCouponPrice() != null && memberBuyCouponParam.getCouponPrice().compareTo(memberCouponDto.getCouponPrice()) == 0)
                {//券类型、券面额相等就OK
                    couponIdList.add(memberCouponDto.getCouponId());
                    number++;
                    if (number.equals(memberBuyCouponParam.getNumber()))
                        break;
                }
            }
            buyCouponParam.setNumber(number);
            buyCouponParam.setCouponIdList(couponIdList);
            returnList.add(buyCouponParam);
        }
        DataSourceHolder.clearDataSource();
        return returnList;
    }

    /**
     * 2.检测当前销售商没有（当前会员购买的券）的数量，即从龙之游渠道购买的数量
     *
     * @param list           会员购买券对象（券类型、面额、数量）
     * @param saleCouponList 销售商出售券对象（券类型、面额、数量）
     * @return
     */
    private List<MemberBuyCouponParam> checkLzyCoupon(List<MemberBuyCouponParam> list, List<MemberBuyCouponParam> saleCouponList) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        List<MemberBuyCouponParam> lzyCouponList = new ArrayList<>();
        for (MemberBuyCouponParam memberBuyCouponParam : list) {
            MemberBuyCouponParam buyCouponParam = new MemberBuyCouponParam();
            buyCouponParam.setCouponType(memberBuyCouponParam.getCouponType());
            buyCouponParam.setCouponPrice(memberBuyCouponParam.getCouponPrice());
            Integer number = 0;//循环条件下，龙之游应销售的数量
            List<Long> couponIdList = new ArrayList<>();//龙之游即将销售的券id集合

            //计算不同类型对应的数量
            for (MemberBuyCouponParam saleCouponParam : saleCouponList) {
                if (memberBuyCouponParam.getCouponType() != null && memberBuyCouponParam.getCouponType().toString().equals(saleCouponParam.getCouponType().toString()) &&
                        memberBuyCouponParam.getCouponPrice() != null && memberBuyCouponParam.getCouponPrice().compareTo(saleCouponParam.getCouponPrice()) == 0
                        ) {//券类型、券面额相等就OK
                    number = memberBuyCouponParam.getNumber().intValue() - saleCouponParam.getNumber().intValue();
                }
            }

            if (number > 0) {
                //查询龙之游即将出售的券
                Pager pager = new Pager();
                pager.setPageNum(1);//页码
                pager.setPageSize(number);//页大小
                CouponDto couponDto = new CouponDto();
                couponDto.setBatch("9899");//批次
                couponDto.setStatus(1);//状态：未绑定
                couponDto.setCategory(memberBuyCouponParam.getCouponType());//券类型
                couponDto.setPrice(memberBuyCouponParam.getCouponPrice());//券面额
                List<CouponDto> lzyList = couponServiceApi.queryCouponList(pager, couponDto).getList();
                for (CouponDto coupon : lzyList) {
                    couponIdList.add(coupon.getId());
                    LOGGER.error("券的价格----------------------------------------------:" + coupon.getPrice());
                }
                buyCouponParam.setCouponIdList(couponIdList);
                buyCouponParam.setNumber(number);
                lzyCouponList.add(buyCouponParam);
            }

        }
        DataSourceHolder.clearDataSource();
        return lzyCouponList;
    }

    /**
     * 3.1.购买销售商的券
     *
     * @param saleManId
     * @param memberId
     * @param saleCouponList 销售商即将售出的券集合
     * @param orderId        订单号
     */
    private Boolean buyOfSaleMan(Long saleManId, Long memberId, List<MemberBuyCouponParam> saleCouponList, String orderId) {
        if (saleCouponList!=null && saleCouponList.size() > 0){
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            for (MemberBuyCouponParam memberBuyCouponParam : saleCouponList) {
                for (Long couponId : memberBuyCouponParam.getCouponIdList()) {
                    //3.1.1.将要卖出去的销售商的券解绑
                    MemberCouponDto memberCouponDto = new MemberCouponDto();
                    memberCouponDto.setMemberId(saleManId);//绑定销售员的会员id
                    memberCouponDto.setCouponId(couponId);//绑定券id
                    if (!memberCouponServiceApi.delete(memberCouponDto)) {
                        LOGGER.error("销售商解绑券失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000001");
                    }

                    //3.1.2.解绑的券绑定到会员
                    memberCouponDto.setMemberId(memberId);//绑定购买方的会员id
                    memberCouponDto.setType(memberBuyCouponParam.getCouponType());
                    memberCouponDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                    if (!memberCouponServiceApi.insert(memberCouponDto)) {
                        LOGGER.error("购买方绑定销售商的券失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000001");
                    }

                    //3.1.4.添加一条销售商券销售记录
                    MemberSaleLogDto memberSaleLogDto = new MemberSaleLogDto();
                    memberSaleLogDto.setSaleMemberId(saleManId);
                    memberSaleLogDto.setBuyMemberId(memberId);
                    memberSaleLogDto.setOrderId(Long.parseLong(orderId));
                    MemberUserDto memberUserDto = memberUserServiceApi.findById(memberId);
                    if (memberUserDto != null) {
                        memberSaleLogDto.setBuyMemberName(memberUserDto.getName());
                    }
                    memberSaleLogDto.setCouponId(couponId);
                    CouponDto coupon = couponServiceApi.selectCouponById(couponId);
                    if (coupon != null) {
                        memberSaleLogDto.setCouponCode(coupon.getCode());
                        memberSaleLogDto.setCouponCategory(coupon.getCategory());
                    }
                    memberSaleLogDto.setType(1);//销售商产品
                    OrderCouponDto orderCouponDto = new OrderCouponDto();
                    orderCouponDto.setCouponId(couponId);
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);

                    //3.1.3.相应的龙币金额充值到销售商可提现余额
                    MemberCouponsDto memberCouponsDto = new MemberCouponsDto();
                    memberCouponsDto.setMemberId(saleManId);
                    memberCouponsDto.setAvailableMoney(memberBuyCouponParam.getCouponPrice());
                    memberCouponsDto.setDragonMoney(memberBuyCouponParam.getCouponPrice());
                    memberCouponsDto.setType(BusinessType.MemberCouponsType.COUPONS.getCode());//卖券收益
                    memberCouponsServiceApi.updateMemberCoupons(memberCouponsDto);

                    List<OrderCouponDto> orderCouponList = orderCouponServiceApi.selectOrderCouponList(orderCouponDto);
                    if (orderCouponList != null && orderCouponList.size() == 1) {
                        Long productId = orderCouponList.get(0).getProductId();
                        memberSaleLogDto.setProductId(productId);
                        ProductInfoDto productInfoDto = productInfoServiceApi.findById(productId);
                        if (productInfoDto != null) {
                            memberSaleLogDto.setProductName(productInfoDto.getName());
                        }
                    }
                    memberSaleLogDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                    if (!memberSaleLogServiceApi.insert(memberSaleLogDto)) {
                        LOGGER.error("销售商-券销售记录新增失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000004");
                    }
                    //3.1.4.添加券与订单的关联关系，用于券的收支详情里面的购买类型
                    CouponOrderLogDto couponOrderLog = new CouponOrderLogDto();
                    couponOrderLog.setOrderId(Long.parseLong(orderId));
                    couponOrderLog.setMemberId(memberId);
                    couponOrderLog.setCouponId(couponId);
                    couponOrderLog.setType(3);//购买
                    if (!couponOrderLogServiceApi.insertCouponOrderLog(couponOrderLog)) {
                        LOGGER.error("销售商-券与订单记录新增失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000005");
                    }
                    //充值相应的龙币到会员账户 2.1
                    LzNumberDTO lbNumberDTO = new LzNumberDTO();
                    lbNumberDTO.setUserId(saleManId);
                    lbNumberDTO.setAddNumber(memberBuyCouponParam.getCouponPrice());
                    payMemberAccountApi.updateNumberLBAdd(lbNumberDTO);//更新龙币到2.1
                    //添加会员账户资金记录 2.1
                    PayBillDTO payBillDTO = new PayBillDTO();
                    payBillDTO.setUserId(saleManId);
                    payBillDTO.setSerialId(Long.parseLong(orderId));
                    payBillDTO.setAmount(memberBuyCouponParam.getCouponPrice());
                    payBillDTO.setRole(CommonConstants.PayMemberAccountRole.shop.getIndex());
                    payBillDTO.setCorrectFlag(CommonConstants.CorrectFlag.CORRECT_FLAG.getIndex());
                    payBillDTO.setType(CommonConstants.BillType.coupons.getIndex());
                    payBillDTO.setDemo("卖券收益");
                    payBillApi.createPayBill(payBillDTO);

                }
            }
            DataSourceHolder.clearDataSource();
        }
        return Boolean.TRUE;
    }

    /**
     * 3.2.购买龙之游的券
     *
     * @param saleManId
     * @param memberId
     * @param lzyCouponList 龙之游即将售出的券集合
     * @param orderId       订单号
     * @return
     */
    private Boolean buyOfLzy(Long saleManId, Long memberId, List<MemberBuyCouponParam> lzyCouponList, String orderId) {
        if (lzyCouponList!=null && lzyCouponList.size() > 0){
            for (MemberBuyCouponParam memberBuyCouponParam : lzyCouponList) {
                for (Long couponId : memberBuyCouponParam.getCouponIdList()) {
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                    //3.2.2.佣金相应的龙币金额充值到销售商龙币冻结余额
                    OrderProductDto orderProductDto = new OrderProductDto();
                    orderProductDto.setMemberId(saleManId);
                    List<OrderProductDto> orderProductDtoList = orderProductServiceApi.selectMemberListByCond(orderProductDto).getList();
                    LOGGER.error("购买龙之游的券---------------List数量："+ orderProductDtoList.size());
                    ProductInfoDto productInfoDto = null;//全局产品对象
                    Long productId = 0L;//全局产品id
                    BigDecimal moneyCount = null;//全局订单金额

                    if (orderProductDtoList != null && orderProductDtoList.size() > 0) {
                        if (orderProductDtoList.size() == 1) {
                            productId = orderProductDtoList.get(0).getProductId();
                        } else {
                            //找到客户买过的金额最大的套餐对应的产品
                            productId = orderProductDtoList.get(0).getProductId();
                            moneyCount = orderProductDtoList.get(0).getMoneyCount();
                            for (OrderProductDto productDto : orderProductDtoList) {
                                if (productDto.getMoneyCount().compareTo(moneyCount) > 0) {
                                    moneyCount = productDto.getMoneyCount();
                                    productId = productDto.getProductId();
                                }
                            }
                        }
                        //根据对应的产品找到佣金相关
                        productInfoDto = productInfoServiceApi.findById(productId);
                        if (productInfoDto != null && productInfoDto.getBenefit() != null) {
                            MemberCouponsDto memberCouponsDto = new MemberCouponsDto();
                            memberCouponsDto.setMemberId(saleManId);
                            memberCouponsDto.setLimitedMoney(memberBuyCouponParam.getCouponPrice().multiply(productInfoDto.getBenefit()).divide(new BigDecimal(100)));
                            memberCouponsDto.setDragonMoney(memberBuyCouponParam.getCouponPrice().multiply(productInfoDto.getBenefit()).divide(new BigDecimal(100)));
                            memberCouponsDto.setType(BusinessType.MemberCouponsType.COMMISSION.getCode());//佣金
                            memberCouponsServiceApi.updateMemberCoupons(memberCouponsDto);
                        }
                        LOGGER.error("购买龙之游的券，产品ID:" + productId);
                    }

                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                    //3.2.1.将准备好的券绑定到会员
                    MemberCouponDto memberCouponDto = new MemberCouponDto();
                    memberCouponDto.setCouponId(couponId);//绑定券id
                    memberCouponDto.setMemberId(memberId);//绑定购买方的会员id
                    memberCouponDto.setType(memberBuyCouponParam.getCouponType());
                    memberCouponDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());

                    CouponDto couponDto = couponServiceApi.selectCouponById(couponId);
                    Ensure.that(couponDto).isNotNull("05000002");
                    if (!memberCouponServiceApi.insert(memberCouponDto)) {
                        LOGGER.error("购买方绑定龙之游的券失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000001");
                    }
                    if (couponDto.getMode() != null && couponDto.getMode().equals(1)) {//领用时间开始计时
                        //截止时间
                        SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date();
                        Long after = (date.getTime() / 1000) + 60 * 60 * 24 * couponDto.getValidTime();
                        date.setTime(after * 1000);
                        String expiryTime = myFmt.format(date);
                        couponDto.setExpiryTime(expiryTime);//过期时间
                        couponDto.setStatus(2);//已绑定
                        couponDto.setChannel(3);
                        String startTime = DateUtil.dateStr3(new Date());
                        couponDto.setStartTime(startTime);
                        Ensure.that(couponServiceApi.updateCouponInfo(couponDto)).isTrue("05000003");
                    }

                    //3.2.3.添加一条销售商券销售记录
                    MemberSaleLogDto memberSaleLogDto = new MemberSaleLogDto();
                    memberSaleLogDto.setSaleMemberId(saleManId);
                    memberSaleLogDto.setBuyMemberId(memberId);
                    memberSaleLogDto.setOrderId(Long.parseLong(orderId));
                    MemberUserDto memberUserDto = memberUserServiceApi.findById(memberId);
                    if (memberUserDto != null) {
                        memberSaleLogDto.setBuyMemberName(memberUserDto.getName());
                    }
                    memberSaleLogDto.setCouponId(couponId);
                    CouponDto coupon = couponServiceApi.selectCouponById(couponId);
                    if (coupon != null) {
                        memberSaleLogDto.setCouponCode(coupon.getCode());
                        memberSaleLogDto.setCouponCategory(coupon.getCategory());
                    }

                    memberSaleLogDto.setType(0);//龙之游产品
                    if (productInfoDto != null && productInfoDto.getBenefit() != null) {
                        LOGGER.error("佣金记录有了，产品ID:" + productId);
                        LOGGER.error("佣金记录有了，佣金：" + productInfoDto.getBenefit());
                        memberSaleLogDto.setProductId(productId);
                        memberSaleLogDto.setProductName(productInfoDto.getName());
                        if (productInfoDto.getBenefit() != null) {
                            memberSaleLogDto.setBenefit(productInfoDto.getBenefit());
                            memberSaleLogDto.setCommission(memberBuyCouponParam.getCouponPrice().multiply(productInfoDto.getBenefit()).divide(new BigDecimal(100)));
                        }
                    }
                    memberSaleLogDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                    if (!memberSaleLogServiceApi.insert(memberSaleLogDto)) {
                        LOGGER.error("龙之游-券销售记录新增失败！" + JSON.toJSONString(memberSaleLogDto));
                        Ensure.that(Boolean.FALSE).isTrue("05000004");
                    }

                    //3.2.4.添加券与订单的关联关系，用于券的收支详情里面的购买类型
                    CouponOrderLogDto couponOrderLog = new CouponOrderLogDto();
                    couponOrderLog.setOrderId(Long.parseLong(orderId));
                    couponOrderLog.setMemberId(memberId);
                    couponOrderLog.setCouponId(couponId);
                    couponOrderLog.setType(3);//购买
                    if (!couponOrderLogServiceApi.insertCouponOrderLog(couponOrderLog)) {
                        LOGGER.error("销售商-券与订单记录新增失败！");
                        Ensure.that(Boolean.FALSE).isTrue("05000005");
                    }
                    DataSourceHolder.clearDataSource();
                }
                DataSourceHolder.clearDataSource();
            }
            DataSourceHolder.clearDataSource();
        }
        return Boolean.TRUE;
    }

    /**
     * 会员通过销售商的二维码，扫码购买券(圆梦计划)
     *
     * @param saleManId 销售商会员id
     * @param memberId  购买方会员id
     * @param list      会员购买券对象（券类型、面额、数量）
     * @param orderId   订单号
     * @return
     */
    public Boolean memberBuyOfCodeDream(Long saleManId, Long memberId, List<MemberBuyCouponParam> list, String orderId) throws ParseException {
        for (MemberBuyCouponParam memberBuyCouponParam : list) {
            if (memberBuyCouponParam.getCouponType() != null) {
                if (memberBuyCouponParam.getCouponType() == 1) {
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                    CouponDto dto = checkCouponBatchAndTypeCode("9799");
                    dto.setType(2);
                    dto.setCategory(1);
                    dto.setRvType(BusinessType.CarCouponType.ALL_DAY_COUPON.getCode());
                    dto.setStartTime(DateUtil.fromNowStartTime());
                    dto.setValidTime(365);
                    dto.setNumber(memberBuyCouponParam.getNumber());
                    dto.setChannel(2);
                    List<Long> ids = couponServiceApi.addCoupon(dto);
                    MemberCouponDto memberCouponDto = new MemberCouponDto();
                    memberCouponDto.setMemberId(memberId);
                    memberCouponDto.setType(1);
                    memberCouponDto.setCouponStatus(2);
                    memberCouponDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                    dto.setMode(BusinessType.CouponMode.COLLAR_TIME.getCode());
                    memberCouponServiceApi.addMemberCoupon(dto, memberCouponDto);
                    addMemberSaleLog(ids, saleManId, dto, memberId, orderId);
                    DataSourceHolder.clearDataSource();
                }
                if (memberBuyCouponParam.getCouponType() == 3) {
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                    CouponDto dto = checkCouponBatchAndTypeCode("9799");
                    dto.setType(2);
                    dto.setCategory(3);
                    dto.setPrice(memberBuyCouponParam.getCouponPrice());
                    dto.setRvType(BusinessType.CarCouponType.ALL_DAY_COUPON.getCode());
                    dto.setStartTime(DateUtil.fromNowStartTime());
                    dto.setValidTime(365);
                    dto.setChannel(2);
                    dto.setNumber(memberBuyCouponParam.getNumber());
                    List<Long> ids = couponServiceApi.addCoupon(dto);
                    MemberCouponDto memberCouponDto = new MemberCouponDto();
                    memberCouponDto.setMemberId(memberId);
                    memberCouponDto.setType(3);
                    memberCouponDto.setCouponStatus(2);
                    memberCouponDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                    dto.setMode(BusinessType.CouponMode.COLLAR_TIME.getCode());
                    memberCouponServiceApi.addMemberCoupon(dto, memberCouponDto);
                    addMemberSaleLog(ids, saleManId, dto, memberId, orderId);
                    DataSourceHolder.clearDataSource();
                }
            }
        }
        return Boolean.TRUE;
    }

    public CouponDto checkCouponBatchAndTypeCode(String batch) {
        CouponDto dto = new CouponDto();
        dto.setBatch(batch);
        for (int i = 0; i < Integer.valueOf(batch); i++) {
            String typeCode = couponServiceApi.selectMaxTypeCode(dto.getBatch());
            if (typeCode != null) {
                if (Integer.valueOf(typeCode) < 9999) {
                    if (typeCode != null && !"".equals(typeCode)) {
                        dto.setTypeCode(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) + 1), 4, "0"));
                    } else {
                        dto.setTypeCode("0001");
                    }
                    break;
                } else {
                    dto.setBatch(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) - 1), 4, "0"));
                    typeCode = couponServiceApi.selectMaxTypeCode(dto.getBatch());
                    if (Integer.valueOf(typeCode) < 9999) {
                        if (typeCode != null && !"".equals(typeCode)) {
                            dto.setTypeCode(StringUtil.leftPad(String.valueOf(Long.parseLong(typeCode) + 1), 4, "0"));
                        } else {
                            dto.setTypeCode("0001");
                        }
                        break;
                    } else {
                        i++;
                    }
                }
            } else {
                dto.setTypeCode("0001");
                break;
            }
        }
        return dto;
    }

    /**
     * 添加购买记录
     *
     * @param ids
     * @param memberId
     */
    private void addMemberSaleLog(List<Long> ids, Long saleManId, CouponDto dto, Long memberId, String orderId) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        for (Long id : ids) {
            MemberSaleLogDto memberSaleLogDto = new MemberSaleLogDto();
            memberSaleLogDto.setSaleMemberId(saleManId);
            memberSaleLogDto.setBuyMemberId(memberId);
            memberSaleLogDto.setOrderId(Long.parseLong(orderId));
            MemberUserDto memberUserDto = memberUserServiceApi.findById(memberId);
            if (memberUserDto != null) {
                memberSaleLogDto.setBuyMemberName(memberUserDto.getName());
            }
            memberSaleLogDto.setCouponId(id);
            CouponDto coupon = couponServiceApi.selectCouponById(id);
            if (coupon != null) {
                memberSaleLogDto.setCouponCode(coupon.getCode());
                memberSaleLogDto.setCouponCategory(coupon.getCategory());
            }

            memberSaleLogDto.setType(2);//龙之游产品
            memberSaleLogDto.setCouponPrice(dto.getPrice());
            if (!memberSaleLogServiceApi.insert(memberSaleLogDto)) {
                LOGGER.error("圆梦计划卖券记录--添加失败！" + JSON.toJSONString(memberSaleLogDto));
                Ensure.that(Boolean.FALSE).isTrue("05000004");
            }

        }
        DataSourceHolder.clearDataSource();
    }


    /**
     * 会员买券(女王节活动)
     *
     * @param saleManId 销售商会员id
     * @param memberId  购买方会员id
     * @param list      会员购买券对象（券类型、面额、数量）
     * @param orderId   订单号
     * @return
     */
    public Boolean memberBuyOfQueenPlan(Long saleManId, Long memberId, List<MemberBuyCouponParam> list, String orderId) throws ParseException {
        for (MemberBuyCouponParam memberBuyCouponParam : list) {
            synchronized (memberBuyCouponParam) {
                if (memberBuyCouponParam.getCouponType() != null) {
                    if (memberBuyCouponParam.getCouponType() == 1) {
                        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                        CouponDto dto = checkCouponBatchAndTypeCode("9799");
                        dto.setType(2);
                        dto.setCategory(1);
                        dto.setRvType(BusinessType.CarCouponType.ALL_DAY_COUPON.getCode());
                        dto.setStartTime(memberBuyCouponParam.getEffectDate());
                        dto.setValidTime(memberBuyCouponParam.getValidTime());
                        dto.setExpiryTime(memberBuyCouponParam.getExpireDate());
                        dto.setNumber(memberBuyCouponParam.getNumber());
                        dto.setMode(BusinessType.CouponMode.COLLAR_TIME.getCode());
                        dto.setChannel(3);
                        List<Long> ids = couponServiceApi.addCouponForQueen(dto);
                        MemberCouponDto memberCouponDto = new MemberCouponDto();
                        memberCouponDto.setMemberId(memberId);
                        memberCouponDto.setType(1);
                        memberCouponDto.setCouponStatus(2);
//                        memberCouponDto.setReceiveTime(memberBuyCouponParam.getEffectDate());
                        memberCouponDto.setCouponPrice(memberBuyCouponParam.getCouponPrice());
                        dto.setMode(BusinessType.CouponMode.GENERATION_TIME.getCode());
                        memberCouponServiceApi.addMemberCoupon(dto, memberCouponDto);
                        addMemberSaleLog(ids, saleManId, dto, memberId, orderId);
                        DataSourceHolder.clearDataSource();
                    }
                }
            }
        }
        return Boolean.TRUE;
    }
}
